package sufutian.com.paypal;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import com.paypal.android.sdk.payments.PayPalAuthorization;
import com.paypal.android.sdk.payments.PayPalConfiguration;
import com.paypal.android.sdk.payments.PayPalFuturePaymentActivity;
import com.paypal.android.sdk.payments.PayPalService;
import com.paypal.android.sdk.payments.PaymentActivity;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import sufutian.com.google_speech.R;

/**
 * Created by sufutian on 2017/7/4.
 */

// AXKuq1NQsy8EHyFAWJFWCZuvmBxQJgf81MUmS08aH1iXTRXG4ClZlstA4F4_mOemIMM3r-QpLV7Y4SQQ   //shahe

//AT2vZTa5RXRJZTd06TR8x3gPHbd7H_E93MYUaczMJ8UspKV4E9mkIvsdQZPhe89wIJI7EqE7QaJDav5Y   live


public class PayAuthoPalActivity extends Activity implements View.OnClickListener, Callback {

    public static final String ENVIRONMENT_PRODUCTION = "live";
    public static final String ENVIRONMENT_SANDBOX = "sandbox";
    public static final String ENVIRONMENT_NO_NETWORK = "mock";


    private Button start_paly;


    private static PayPalConfiguration config = new PayPalConfiguration()

            // Start with mock environment.  When ready, switch to sandbox (ENVIRONMENT_SANDBOX)
            // or live (ENVIRONMENT_PRODUCTION)
            .environment(PayPalConfiguration.ENVIRONMENT_NO_NETWORK)

            .clientId("AXKuq1NQsy8EHyFAWJFWCZuvmBxQJgf81MUmS08aH1iXTRXG4ClZlstA4F4_mOemIMM3r-QpLV7Y4SQQ")
            // Minimally, you will need to set three merchant information properties.
            // These should be the same values that you provided to PayPal when you registered your app.
            .merchantName("Yigo Space Beijing Science Technology Co Ltd")
            .merchantPrivacyPolicyUri(Uri.parse("https://www.example.com/privacy"))
            .merchantUserAgreementUri(Uri.parse("https://www.example.com/legal"));


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_paypal);
        start_paly = (Button) findViewById(R.id.start_paly);
        start_paly.setOnClickListener(this);


        Intent intent = new Intent(this, PayPalService.class);

        intent.putExtra(PayPalService.EXTRA_PAYPAL_CONFIGURATION, config);

        startService(intent);


    }


    @Override
    protected void onDestroy() {
        stopService(new Intent(this, PayPalService.class));
        super.onDestroy();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.start_paly:
                onFuturePaymentPurchasePressed();
                break;
        }
    }


    public void onFuturePaymentPurchasePressed() {

        // PAYMENT_INTENT_SALE will cause the payment to complete immediately.
        // Change PAYMENT_INTENT_SALE to
        //   - PAYMENT_INTENT_AUTHORIZE to only authorize payment and capture funds later.
        //   - PAYMENT_INTENT_ORDER to create a payment for authorization and capture
        //     later via calls from your server.


//        PayPalPayment payment = new PayPalPayment(new BigDecimal("0.01"), "USD", "PayPal支付",
//                PayPalPayment.PAYMENT_INTENT_SALE);
//
//        Intent intent = new Intent(this, PaymentActivity.class);
//
//        // send the same configuration for restart resiliency
//        intent.putExtra(PayPalService.EXTRA_PAYPAL_CONFIGURATION, config);
//
//        intent.putExtra(PaymentActivity.EXTRA_PAYMENT, payment);
//
//        startActivityForResult(intent, 0);


        Intent intent = new Intent(PayAuthoPalActivity.this, PayPalFuturePaymentActivity.class);

        // send the same configuration for restart resiliency
        intent.putExtra(PayPalService.EXTRA_PAYPAL_CONFIGURATION, config);

        startActivityForResult(intent, 0);

    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == Activity.RESULT_OK) {
            PayPalAuthorization auth = data
                    .getParcelableExtra(PayPalFuturePaymentActivity.EXTRA_RESULT_AUTHORIZATION);
            if (auth != null) {
                try {
                    String authorization_code = auth.getAuthorizationCode();

                    sendAuthorizationToServer(auth);

                } catch (Exception e) {
                    Log.e("FuturePaymentExample", "an extremely unlikely failure occurred: ", e);
                }
            }
        } else if (resultCode == Activity.RESULT_CANCELED) {
            Toast.makeText(this, "Cancel the payment", Toast.LENGTH_SHORT).show();
        } else if (resultCode == PaymentActivity.RESULT_EXTRAS_INVALID) {
            Toast.makeText(this, "Payment error", Toast.LENGTH_SHORT).show();
        }
    }


    private void sendAuthorizationToServer(PayPalAuthorization authorization) {

        // TODO:
        // Send the authorization response to your server, where it can exchange the authorization code
        // for OAuth access and refresh tokens.
        //
        // Your server must then store these tokens, so that your server code can execute payments
        // for this user in the future.


        String metadataId = PayPalConfiguration.getClientMetadataId(this);

    }


    public void getDetails(String id) {
        OkHttpClient client = new OkHttpClient().newBuilder()
                .connectTimeout(10, TimeUnit.SECONDS)//设置超时时间
                .readTimeout(10, TimeUnit.SECONDS)//设置读取超时时间
                .writeTimeout(10, TimeUnit.SECONDS)//设置写入超时时间
                .build();

        String requestUrl = "https://api.sandbox.paypal.com/v1/payments/payment" + "/" + id;

        Request.Builder requestBuilder = new Request.Builder()
                .url(requestUrl)
                .get();

        try {
            client.newCall(requestBuilder.build()).enqueue(this);
        } catch (Exception e) {
            e.printStackTrace();
        }


    }

    @Override
    public void onFailure(Call call, IOException e) {
        e.printStackTrace();
        Log.e("sufutian", "onFailure: ");
    }

    @Override
    public void onResponse(Call call, Response response) throws IOException {
        String string = response.body().string();
        Log.e("sufutian==", "onResponse " + string);
    }
}
